package com.central.scheduler.service.queue;

import com.central.scheduler.service.exception.TaskPriorityQueueException;
import org.springframework.stereotype.Service;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author Tindy
 * @date 2021/12/20
 * @describe
 * A singleton of a task queue implemented using PriorityBlockingQueue
 */
@Service
public class TaskPriorityQueueImpl implements TaskPriorityQueue<TaskPriority> {
    /**
     * queue size
     */
    private static final Integer QUEUE_MAX_SIZE = 3000;

    /**
     * queue
     */
    private PriorityBlockingQueue<TaskPriority> queue = new PriorityBlockingQueue<>(QUEUE_MAX_SIZE);

    /**
     * put task takePriorityInfo
     *
     * @param taskPriorityInfo takePriorityInfo
     * @throws TaskPriorityQueueException
     */
    @Override
    public void put(TaskPriority taskPriorityInfo) throws TaskPriorityQueueException {
        queue.put(taskPriorityInfo);
    }

    /**
     * take taskInfo
     *
     * @return taskInfo
     * @throws TaskPriorityQueueException
     */
    @Override
    public TaskPriority take() throws TaskPriorityQueueException, InterruptedException {
        return queue.take();
    }

    /**
     * poll taskInfo with timeout
     *
     * @param timeout
     * @param unit
     * @return
     * @throws TaskPriorityQueueException
     * @throws InterruptedException
     */
    @Override
    public TaskPriority poll(long timeout, TimeUnit unit) throws TaskPriorityQueueException, InterruptedException {
        return queue.poll(timeout,unit);
    }

    /**
     * queue size
     *
     * @return size
     * @throws TaskPriorityQueueException
     */
    @Override
    public int size() throws TaskPriorityQueueException {
        return queue.size();
    }
}
